import Vue from 'vue'
import VueRouter from 'vue-router'
import Home from '../views/Home.vue'
import Login from '../views/Login.vue'
import NotFound from '../views/NotFound.vue'
import store from '../store/index'

Vue.use(VueRouter)

// 一个路由就是一个对象
const oneRoutes = { path: 'one', component: () => import('@/views/Page1.vue')}
const twoRoutes = { path: 'two', component: () => import('@/views/Page2.vue')}
const threeRoutes =  { path: 'three', component: () => import('@/views/Page3.vue')}

// 将路由映射出来
const Routers = {
  'one': oneRoutes,
  'two': twoRoutes,
  'three': threeRoutes
}

const routes = [
  {
    path: '/',
    name: 'Home',
    component: Home,
    redirect: 'one',
    children: [
    ]
  },
  {
    path: '/login',
    name: 'Login',
    component: Login
  },
  {
    path: '*',
    name: 'NotFound',
    component: NotFound
  }
]

const router = new VueRouter({routes})

// 路由导航守卫
router.beforeEach((to, from, next) => {      
  if(to.path === '/login') { // 访问登录页，直接放行
    next()
  }else {
    const token = sessionStorage.getItem('token') 
    if(!token) {  // 要访问其他页面，没有token的情况下强制跳转到登录页
      next('/login')
    } else { 
      next()
    }
  }
}) 

export function dynamicRouting() { // 导出动态路由
  // 根据路由权限，对路由规则动态添加
  // console.log(router);
  const right = store.state.rights
  // console.log(right);
  right.forEach(item => {
    item.children.forEach(item => {
      // console.log('item.path:',item.path);
      // console.log('router:',router);
      const temp =  Routers[item.path] //匹配到定义好的路由
      temp.meta = item.rights // 动态添加路由的meta属性
      router.options.routes[0].children.push(temp) // 将匹配到的路由加入到children中去（假如没有加进去的，在url里面直接访问是访问不到的）
    })
  })
  router.addRoutes(router.options.routes) // 将新的路由加入到router中
}

const originalPush = VueRouter.prototype.push
// 重写了原型上的push方法，统一的处理了错误信息
VueRouter.prototype.push = function push (location) {
  return originalPush.call(this, location).catch(err => err)
}

export default router
